'use client'
import { useState, useEffect } from 'react'
import './globals.css'
import 'katex/dist/katex.min.css'

export default function NotePage({ params }) {
  const [text, setText] = useState('')
  const [html, setHtml] = useState('')
  const [isShareMode, setIsShareMode] = useState(false)

  useEffect(() => {
    const init = async () => {
      setIsShareMode(window.location.hash === '#fenxiang')
      const initialText = decodeURIComponent(params.noteId || '').replace(/-/g, '\n')
      if (initialText) {
        setText(initialText)
        const { default: remark } = await import('remark')
        const { default: html } = await import('remark-html')
        const { default: math } = await import('remark-math')
        const { default: katex } = await import('rehype-katex')
        
        const result = await remark()
          .use(math)
          .use(html, { sanitize: false })
          .use(katex)
          .process(initialText)
        setHtml(result.toString())
      }
    }
    init()
  }, [params.noteId])

  useEffect(() => {
    const update = async () => {
      if (!text) return
      const { default: remark } = await import('remark')
      const { default: html } = await import('remark-html')
      const { default: math } = await import('remark-math')
      const { default: katex } = await import('rehype-katex')
      
      const result = await remark()
        .use(math)
        .use(html, { sanitize: false })
        .use(katex)
        .process(text)
      setHtml(result.toString())
      
      if (!isShareMode) {
        window.history.replaceState({}, '', `/${encodeURIComponent(text.replace(/\n/g, '-'))}`)
      }
    }
    const timer = setTimeout(update, 300)
    return () => clearTimeout(timer)
  }, [text, isShareMode])

  const handleShare = () => {
    navigator.clipboard.writeText(
      `${window.location.origin}/${encodeURIComponent(text.replace(/\n/g, '-'))}#fenxiang`
    )
  }

  if (isShareMode) {
    return <div className="markdown" dangerouslySetInnerHTML={{ __html: html }} />
  }

  return (
    <div className="container">
      <div className="editor">
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="输入Markdown内容..."
          autoFocus
        />
      </div>
      <div className="preview">
        <div className="markdown" dangerouslySetInnerHTML={{ __html: html }} />
      </div>
      <button className="share-btn" onClick={handleShare}>分享</button>
    </div>
  )
}
